package com.controller;



import com.alibaba.fastjson.JSONObject;
import com.domain.DownloadPassword;
import com.webservice.FileService;
import net.sf.json.JSONException;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping(value="/postFile.action",method = RequestMethod.POST)
    @ResponseBody
    public String postFile(@RequestParam("file") MultipartFile file) throws IOException {


        String path = "D:/apache-tomcat-8.5.57/webapps/mmms/mmms-assets/";
        String name = file.getContentType();
        String fileName = file.getOriginalFilename();
//        System.out.println(name);
//        System.out.println(fileName);
        if(file.isEmpty()){
//            System.out.println("fail");
            return "fail";
            //return "successful";
        }else{
//            System.out.println("successful");

            file.transferTo(new File(path+fileName));
            return fileName;
            //return "fail";
        }
    }

    @RequestMapping(value="/getFile.action",method = RequestMethod.GET)
    @ResponseBody
    public String getFile(HttpServletRequest request){

        String fileName = request.getParameter("fileName");
        File file = new File("D:/apache-tomcat-8.5.57/webapps/mmms/mmms-assets/"+fileName);
        if (file.exists()){
            FileInputStream fis = null;
            try {
                fis = new FileInputStream("D:/apache-tomcat-8.5.57/webapps/mmms/mmms-assets/"+fileName);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // 创建保存要上传的图像文件内容的字节数组
            byte[] buffer = new byte[(int) file.length()];
            // 将图像文件的内容读取buffer数组中
            int n = 0;
            try {
                if (fis!=null){
                    n = fis.read(buffer);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                if (fis!=null) {
                    fis.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String uploadbuffer = Base64.getEncoder().encodeToString(buffer);
            return uploadbuffer;
        }
        return "fail";
    }


    @ResponseBody
    @RequestMapping("/getApkVersion")
    public Map getApkVersion(){
        String version = fileService.findFile("mmms").getFileVersion();
        String url = fileService.findFile("mmms").getFileUrl();
        Map<String ,String> map = new HashMap<>();
        map.put("version",version);
        map.put("url",url);
        return map;
    }

    @RequestMapping("/getDownloadValue")
    @ResponseBody
    public Map getDownloadValue() {

        DownloadPassword downloadPassword = fileService.findDownloadValue("downloadAPP");
        Map<String, String > map = new HashMap<>();
        if (downloadPassword != null){
            map.put("downloadKey", downloadPassword.getDownloadKey());
            map.put("downloadValue", downloadPassword.getDownloadValue());
        }
        return map;
    }




    @RequestMapping("/bigFileUpload")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        long serialVersionUID = 1L;
        String fileName="";
        boolean success=false;
//        System.out.println("开始接受文件");
        String temp="D:/temp";   //临时目录
//        System.out.println("temp="+temp);
        String loadpath="D:/mmms-assets"; //上传文件存放目录
//        System.out.println("loadpath="+loadpath);
        DiskFileUpload fu =new DiskFileUpload();
        fu.setSizeMax(1024*1024*1024);   // 设置允许用户上传文件大小,单位:字节
        fu.setSizeThreshold(4096);   // 设置最多只允许在内存中存储的数据,单位:字节
        fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

        //开始读取上传信息
        int index=0;
        List fileItems =null;
        try {
            fileItems = fu.parseRequest(request);
//            System.out.println("fileItems="+fileItems);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
        while (iter.hasNext())
        {
            FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表单信息
            if (!item.isFormField())
            {
                fileName = item.getName();//获取上传文件名,包括路径
                fileName=fileName.substring(fileName.lastIndexOf("\\")+1);//从全路径中提取文件名
                long size = item.getSize();
                if((fileName.equals("")) && size==0)
                    continue;
                int point = fileName.indexOf(".");
                fileName=(new Date()).getTime()+fileName.substring(point,fileName.length());
                index++;
                File fNew=new File(loadpath, fileName);
                try {
                    item.write(fNew);
                    success=true;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    success=false;
                    e.printStackTrace();
                }
            }
            else//取出不是文件域的所有表单信息
            {    String fieldName=item.getFieldName();
                String fieldvalue = item.getString();
                //如果包含中文应写为：(转为UTF-8编码)
//                System.out.println(fieldName);
//                System.out.println(fieldvalue);
//                       String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
            }
        }

        JSONObject json=new JSONObject();
        try {
            if(success){
                String imgPath="image/"+fileName.substring(0, fileName.length());

                json.put("error_code", 1);
                json.put("msg", "upload success");
                json.put("imgPath", imgPath);

            }else{
                json.put("error_code", 0);
                json.put("msg", "upload fail");
                json.put("imgPath", "");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        response.getWriter().append(json.toString());
//               response.sendRedirect("result.jsp?imgPath="+ json.toString());
    }


    /**
     * 下载大文件
     * @param fileName
     * @return
     * @throws IOException
     */
    @RequestMapping("/downloadBigFile")
    public ResponseEntity<byte[]> downloadFile(String fileName) throws IOException {
        //System.out.println("接口开始执行-->downloadFile");

        File file = new File("D:/mmms-assets/"+fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(file.length());

        //System.out.println(file.length() + " is length,..");

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }



    /**
     * ↓通过Java API: file.transferTo()保存上传的单个文件
     */
    @RequestMapping("/uploadFileByJava")
    @ResponseBody
    public String uploadFileByJava(@RequestParam("file") CommonsMultipartFile file){
        //System.out.println("接口开始执行-->uploadFileByJava");


        try {
            file.transferTo(new File("D:/mmms-assets/" + file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "uploadFileByJava suc... ";
    }


    /**
     * ↓通过Spring API保存上传的多个文件
     */
    @RequestMapping("/uploadFilesBySpring")
    @ResponseBody
        public Map uploadFilesBySpring(HttpServletRequest request)  {
//            System.out.println("接口开始执行-->uploadFilesBySpring");
            Map<String,String> result = new HashMap<>();
            String desPath;
            StringBuilder builder=new StringBuilder();
        try {
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

                Iterator<String> iterator = multiRequest.getFileNames();

                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iterator.next());

                    if (null != file) {
                        desPath = "D:/mmms-assets/" + file.getOriginalFilename();
                        try {
                            file.transferTo(new File(desPath));
                            builder.append(file.getOriginalFilename());
                            builder.append(",");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            String fileNames= builder.toString();
            result.put("code","1");
            result.put("msg",fileNames.substring(0,fileNames.length()-1));
        }catch (Exception e){
            result.put("code","0");
            result.put("msg","uploadError");
        }
        return result;
    }




}
